<template>
    <a-space direction="vertical" :style="{ width: '100%', height: '100vh' }" :size="[0, 0]">
      <a-layout style="height: 100vh">
        <!-- 顶部导航栏 -->
        <a-layout-header :style="headerStyle">
          <div class="header-content">
            <div class="header-left">
              <a-button type="text" @click="goBack" style="color: white; margin-right: 16px">
                <template #icon><arrow-left-outlined /></template>
                返回任务中心
              </a-button>
              <h2 style="color: white; margin: 0;">{{ task?.title || '任务执行' }}</h2>
            </div>
            <div class="header-right">
              <a-tag color="blue" v-if="task?.type">{{ getTaskTypeLabel(task.type) }}</a-tag>
              <a-tag :color="getStatusColor(task?.status)" v-if="task?.status">
                {{ getStatusLabel(task?.status) }}
              </a-tag>
            </div>
          </div>
        </a-layout-header>
        
        <a-layout>
          <!-- 左侧步骤面板 -->
          <a-layout-sider :style="siderStyle" width="300">
            <div class="steps-panel">
              <div class="steps-header">
                <h3>任务步骤</h3>
                <div class="progress-info">
                  <span class="progress-text">{{ completedSteps }}/{{ totalSteps }}</span>
                  <a-progress 
                    :percent="progressPercent" 
                    :show-info="false" 
                    size="small"
                    :stroke-color="progressColor"
                  />
                </div>
              </div>
              
              <div class="steps-list">
                <div 
                  v-for="(step, index) in taskSteps" 
                  :key="step.id"
                  class="step-item"
                  :class="{
                    'step-active': currentStepIndex === index,
                    'step-completed': step.completionStatus === 'completed',
                    'step-in-progress': step.completionStatus === 'in_progress',
                    'step-failed': step.completionStatus === 'failed',
                    'step-skipped': step.completionStatus === 'skipped'
                  }"
                  @click="selectStep(index)"
                >
                  <div class="step-header">
                    <div class="step-order">{{ step.stepOrder }}</div>
                    <div class="step-info">
                      <div class="step-title">{{ step.title }}</div>
                      <div class="step-meta">
                        <a-tag size="small" :color="getStepTypeColor(step.stepType)">
                          {{ getStepTypeLabel(step.stepType) }}
                        </a-tag>
                        <span class="step-time" v-if="step.estimatedTime">
                          {{ step.estimatedTime }}分钟
                        </span>
                      </div>
                    </div>
                    <div class="step-status">
                      <check-circle-outlined v-if="step.completionStatus === 'completed'" class="status-icon completed" />
                      <clock-circle-outlined v-else-if="step.completionStatus === 'in_progress'" class="status-icon in-progress" />
                      <close-circle-outlined v-else-if="step.completionStatus === 'failed'" class="status-icon failed" />
                      <minus-circle-outlined v-else-if="step.completionStatus === 'skipped'" class="status-icon skipped" />
                      <circle-outlined v-else class="status-icon not-started" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </a-layout-sider>
          
          <!-- 右侧内容区域 -->
          <a-layout-content :style="contentStyle">
            <div class="content-area">
              <!-- 任务简介 -->
              <div class="task-intro" v-if="task">
                <a-card title="任务简介" :bordered="false">
                  <p class="task-description">{{ task.description }}</p>
                  <div class="task-meta">
                    <a-descriptions :column="3" size="small">
                      <a-descriptions-item label="截止时间">
                        {{ formatDate(task.deadline) }}
                      </a-descriptions-item>
                      <a-descriptions-item label="难度">
                        <a-tag :color="getDifficultyColor(task.difficulty)">
                          {{ getDifficultyLabel(task.difficulty) }}
                        </a-tag>
                      </a-descriptions-item>
                      <a-descriptions-item label="预计用时">
                        {{ task.estimatedTime || '未知' }} 分钟
                      </a-descriptions-item>
                    </a-descriptions>
                  </div>
                </a-card>
              </div>
              
              <!-- 当前步骤内容 -->
              <div class="current-step" v-if="currentStep">
                <a-card :title="`步骤 ${currentStep.stepOrder}: ${currentStep.title}`" :bordered="false">
                  <div class="step-content">
                    <div class="step-description">
                      <h4>步骤说明</h4>
                      <p>{{ currentStep.description }}</p>
                    </div>
                    
                    <div class="step-details" v-if="currentStep.content">
                      <h4>详细内容</h4>
                      <div class="content-display" v-html="currentStep.content"></div>
                    </div>
                    
                    <div class="step-requirements" v-if="currentStep.requirements">
                      <h4>完成要求</h4>
                      <p>{{ currentStep.requirements }}</p>
                    </div>
                    
                    <div class="step-actions">
                      <a-space>
                        <a-button 
                          type="primary" 
                          @click="markStepCompleted"
                          v-if="currentStep.completionStatus !== 'completed'"
                        >
                          标记完成
                        </a-button>
                        <a-button 
                          @click="markStepInProgress"
                          v-if="currentStep.completionStatus === 'not_started'"
                        >
                          开始进行
                        </a-button>
                        <a-button 
                          @click="resetStep"
                          v-if="currentStep.completionStatus === 'completed'"
                        >
                          重新开始
                        </a-button>
                        <a-button 
                          @click="skipStep"
                          v-if="currentStep.canSkip && currentStep.completionStatus !== 'skipped'"
                        >
                          跳过步骤
                        </a-button>
                      </a-space>
                    </div>
                  </div>
                </a-card>
              </div>
              
              <!-- 步骤导航 -->
              <div class="step-navigation" v-if="taskSteps.length > 1">
                <a-card :bordered="false">
                  <a-space>
                    <a-button 
                      @click="previousStep"
                      :disabled="currentStepIndex === 0"
                    >
                      <template #icon><left-outlined /></template>
                      上一步
                    </a-button>
                    <a-button 
                      @click="nextStep"
                      :disabled="currentStepIndex === taskSteps.length - 1"
                    >
                      下一步
                      <template #icon><right-outlined /></template>
                    </a-button>
                    <a-button 
                      type="primary" 
                      @click="completeTask"
                      v-if="isAllStepsCompleted"
                    >
                      完成任务
                    </a-button>
                  </a-space>
                </a-card>
              </div>
              
              <!-- 空状态 -->
              <div v-if="!currentStep && !loading" class="no-steps">
                <a-empty description="暂无步骤信息" />
              </div>
              
              <!-- 加载状态 -->
              <div v-if="loading" class="loading-container">
                <a-spin size="large" />
                <p>正在加载步骤信息...</p>
              </div>
            </div>
          </a-layout-content>
        </a-layout>
        
        <!-- 底部状态栏 -->
        <a-layout-footer :style="footerStyle">
          <div class="footer-content">
            <span>当前步骤: {{ currentStepIndex + 1 }} / {{ totalSteps }}</span>
            <span>完成进度: {{ progressPercent }}%</span>
            <span>预计剩余时间: {{ estimatedRemainingTime }} 分钟</span>
          </div>
        </a-layout-footer>
      </a-layout>
    </a-space>
  </template>
  
  <script setup>
  import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { message } from 'ant-design-vue'
  import { 
    ArrowLeftOutlined, 
    CheckCircleOutlined, 
    ClockCircleOutlined, 
    CloseCircleOutlined, 
    MinusCircleOutlined, 
    CircleOutlined,
    LeftOutlined,
    RightOutlined
  } from '@ant-design/icons-vue'
  import { getTaskDetail } from '../api/task'
  import { getTaskStepsTree } from '../api/taskStep'
  import { getAuth } from '../utils/auth'
  
  // 路由和状态
  const route = useRoute()
  const router = useRouter()
  const taskId = route.params.id
  
  // 响应式数据
  const task = ref(null)
  const taskSteps = ref([])
  const currentStepIndex = ref(0)
  const loading = ref(false)
  
  // 样式配置
  const headerStyle = {
    height: 64,
    paddingInline: 24,
    backgroundColor: '#001529',
    borderBottom: '1px solid #f0f0f0'
  }
  
  const contentStyle = {
    padding: '24px',
    backgroundColor: '#f5f5f5',
    minHeight: 'calc(100vh - 64px - 48px)'
  }
  
  const siderStyle = {
    backgroundColor: '#fff',
    borderRight: '1px solid #f0f0f0'
  }
  
  const footerStyle = {
    height: 48,
    paddingInline: 24,
    backgroundColor: '#fafafa',
    borderTop: '1px solid #f0f0f0',
    textAlign: 'center'
  }
  
  // 计算属性
  const currentStep = computed(() => {
    if (taskSteps.value.length === 0 || currentStepIndex.value >= taskSteps.value.length) {
      return null
    }
    return taskSteps.value[currentStepIndex.value]
  })
  
  const totalSteps = computed(() => taskSteps.value.length)
  
  const completedSteps = computed(() => {
    return taskSteps.value.filter(step => step.completionStatus === 'completed').length
  })
  
  const progressPercent = computed(() => {
    if (totalSteps.value === 0) return 0
    return Math.round((completedSteps.value / totalSteps.value) * 100)
  })
  
  const progressColor = computed(() => {
    if (progressPercent.value >= 80) return '#52c41a'
    if (progressPercent.value >= 50) return '#faad14'
    return '#1890ff'
  })
  
  const isAllStepsCompleted = computed(() => {
    return completedSteps.value === totalSteps.value && totalSteps.value > 0
  })
  
  const estimatedRemainingTime = computed(() => {
    const remainingSteps = taskSteps.value.filter(step => 
      step.completionStatus !== 'completed' && step.completionStatus !== 'skipped'
    )
    return remainingSteps.reduce((total, step) => total + (step.estimatedTime || 0), 0)
  })
  
  // 方法
  const goBack = () => {
    router.push({ name: 'student-tasks' })
  }
  
  const loadTask = async () => {
    try {
      loading.value = true
      const response = await getTaskDetail(taskId)
      task.value = response.data
    } catch (error) {
      console.error('加载任务失败:', error)
      message.error('加载任务信息失败')
    } finally {
      loading.value = false
    }
  }
  
  const loadTaskSteps = async () => {
    try {
      const response = await getTaskStepsTree({ taskId })
      taskSteps.value = response.data || []
      
      // 如果有步骤，选择第一个未完成的步骤
      if (taskSteps.value.length > 0) {
        const firstIncompleteIndex = taskSteps.value.findIndex(step => 
          step.completionStatus !== 'completed'
        )
        currentStepIndex.value = firstIncompleteIndex >= 0 ? firstIncompleteIndex : 0
      }
    } catch (error) {
      console.error('加载任务步骤失败:', error)
      message.error('加载任务步骤失败')
    }
  }
  
  const selectStep = (index) => {
    if (index >= 0 && index < taskSteps.value.length) {
      currentStepIndex.value = index
    }
  }
  
  const markStepCompleted = () => {
    if (currentStep.value) {
      currentStep.value.completionStatus = 'completed'
      message.success('步骤已完成')
      
      // 自动跳转到下一步
      if (currentStepIndex.value < taskSteps.value.length - 1) {
        nextStep()
      }
    }
  }
  
  const markStepInProgress = () => {
    if (currentStep.value) {
      currentStep.value.completionStatus = 'in_progress'
      message.info('步骤已开始进行')
    }
  }
  
  const resetStep = () => {
    if (currentStep.value) {
      currentStep.value.completionStatus = 'not_started'
      message.info('步骤已重置')
    }
  }
  
  const skipStep = () => {
    if (currentStep.value && currentStep.value.canSkip) {
      currentStep.value.completionStatus = 'skipped'
      message.info('步骤已跳过')
      
      // 自动跳转到下一步
      if (currentStepIndex.value < taskSteps.value.length - 1) {
        nextStep()
      }
    }
  }
  
  const previousStep = () => {
    if (currentStepIndex.value > 0) {
      currentStepIndex.value--
    }
  }
  
  const nextStep = () => {
    if (currentStepIndex.value < taskSteps.value.length - 1) {
      currentStepIndex.value++
    }
  }
  
  const completeTask = () => {
    message.success('恭喜！任务已完成')
    // 这里可以添加完成任务后的逻辑，比如跳转或显示结果
  }
  
  // 工具方法
  const getTaskTypeLabel = (type) => {
    const typeMap = {
      'coding': '编程练习',
      'quiz': '知识测验',
      'project': '项目作业',
      'reading': '阅读任务'
    }
    return typeMap[type] || type
  }
  
  const getStatusLabel = (status) => {
    const statusMap = {
      'pending': '待完成',
      'in-progress': '进行中',
      'completed': '已完成',
      'PENDING': '待完成',
      'IN_PROGRESS': '进行中',
      'COMPLETED': '已完成'
    }
    return statusMap[status] || status
  }
  
  const getStatusColor = (status) => {
    const colorMap = {
      'pending': 'orange',
      'in-progress': 'blue',
      'completed': 'green',
      'PENDING': 'orange',
      'IN_PROGRESS': 'blue',
      'COMPLETED': 'green'
    }
    return colorMap[status] || 'default'
  }
  
  const getDifficultyLabel = (difficulty) => {
    const difficultyMap = {
      'easy': '简单',
      'medium': '中等',
      'hard': '困难'
    }
    return difficultyMap[difficulty] || difficulty
  }
  
  const getDifficultyColor = (difficulty) => {
    const colorMap = {
      'easy': 'green',
      'medium': 'orange',
      'hard': 'red'
    }
    return colorMap[difficulty] || 'default'
  }
  
  const getStepTypeLabel = (stepType) => {
    const typeMap = {
      'instruction': '说明',
      'coding': '编程',
      'quiz': '测验',
      'upload': '上传',
      'review': '审核'
    }
    return typeMap[stepType] || stepType
  }
  
  const getStepTypeColor = (stepType) => {
    const colorMap = {
      'instruction': '#1890ff',
      'coding': '#52c41a',
      'quiz': '#faad14',
      'upload': '#722ed1',
      'review': '#eb2f96'
    }
    return colorMap[stepType] || '#666'
  }
  
  const formatDate = (dateString) => {
    if (!dateString) return '未设置'
    try {
      return new Date(dateString).toLocaleDateString('zh-CN')
    } catch (error) {
      return '日期格式错误'
    }
  }
  
  // 生命周期
  onMounted(async () => {
    await loadTask()
    await loadTaskSteps()
  })
  
  onUnmounted(() => {
    // 清理工作
  })
  </script>
  
  <style scoped>
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100%;
  }
  
  .header-left {
    display: flex;
    align-items: center;
  }
  
  .header-right {
    display: flex;
    gap: 8px;
  }
  
  .steps-panel {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  
  .steps-header {
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .steps-header h3 {
    margin: 0 0 12px 0;
    color: #262626;
  }
  
  .progress-info {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .progress-text {
    font-size: 12px;
    color: #8c8c8c;
    min-width: 40px;
  }
  
  .steps-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
  }
  
  .step-item {
    padding: 12px;
    margin-bottom: 8px;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
    background: #fff;
  }
  
  .step-item:hover {
    border-color: #1890ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
  }
  
  .step-item.step-active {
    border-color: #1890ff;
    background: #e6f7ff;
  }
  
  .step-item.step-completed {
    border-color: #52c41a;
    background: #f6ffed;
  }
  
  .step-item.step-in-progress {
    border-color: #faad14;
    background: #fffbe6;
  }
  
  .step-item.step-failed {
    border-color: #ff4d4f;
    background: #fff1f0;
  }
  
  .step-item.step-skipped {
    border-color: #d9d9d9;
    background: #f5f5f5;
  }

  </style>